// pages/o2oHome/o2oHome.js
let location = require("../../../mybehaviors/location/location");
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');

let app = getApp();
Page({
  behaviors: [location,skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    open_store_cart: false,
    address: "",
    point: {
      lat: "",
      lng: "",
    },
    city: "",
    page: 1,
    ads: [],
    total_page: 0,
    category: [],
    loading: false,
    isLoadMore: true,
    stores: [],
    carousels: [],
    bannerData: [],
    // 选项卡
    shop: "",
    is_open: 0,
    Height: 0,
    LastHeight: 0,

    hot_arrondi:{},//热门团购模块信息
    plugin_name:'拓客卡',
    openTemplate: 0, //门店列表样式
    imgPath: app.globalData.imgPath
  },

  /**
   * 生命周期函数--监听页面加载
   */
  gettitle(){
    let basic_info = wx.getStorageSync("yz_basic_info");
    let title = "";
    if(basic_info&&basic_info.home&&basic_info.home.mailInfo){
      title = basic_info.home.mailInfo.name || "";
    }
    console.log(basic_info.home.mailInfo.name,'basic_info.home.mailInfo.name')
    wx.setNavigationBarTitle({
      title
    });
  },
  onLoad: function (options) {
    if (options.mid) {
      app._setMid(options.mid);
    }
    if (options.addressData) {
      let addressData = JSON.parse(options.addressData);
      this.setData({
        "point.lat": addressData.latitude,
        "point.lng": addressData.longitude,
        address: addressData.title,
        title: addressData.title,
        city: addressData.city,
      });
      this.getStorePage();
    } else {
      this._getLocation((res) => {
        let address_on = wx.getStorageSync('address-point');
        this.setData({
          address:address_on.city
        });
        this.getStorePage();
      },(err)=>{
        this.getStorePage();
      });
    }
    // console.log(this.data.city)
  },
  imgHeight: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    var swiperH = (winWid * imgh) / imgw + "px"; //等比设置swiper的高度。 即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度  ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    if (parseInt(swiperH) > this.data.LastHeight) {
      this.setData({
        Height: swiperH, //设置高度
      });
      this.data.LastHeight = parseInt(swiperH);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.storeList = this.selectComponent("#storeList");
    this.business = this.selectComponent("#business");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // if (!this.data.loading) {
    if (this.data.stores.length > 0 && !this.data.is_open) {
      this.storeList.getMoreStores();
    }
    if (this.data.shop && this.data.is_open) {
      this.business.getMoreList();
    }
    // this.getMoreData();
    // } else {
    //   console.log("没有更多了");
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline: function () {
    let value = wx.getStorageSync("yz_uid");
    let mid = "";
    if (value) {
      mid = value;
    }
    return {
      title: "",
      path: "packageC/o2o/o2oHome/o2oHome?mid=" + mid,
      // query: `mid=${mid}`
    };
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      path: "/packageC/o2o/o2oHome/o2oHome?mid=" + mid,
    };
  },

  getStores(data) {
    this.setData({
      total_page: data.last_page,
    });
    if (!this.data.total_page) {
      this.setData({
        total_page: 0,
      });
    }

    if (data.total <= 0 || data.current_page == data.last_page) {
      this.setData({
        isLoadMore: false,
      });
    }
    this.setData({
      stores: data.data,
    });
  },
  //默认首页数据
  _indexData(data) {
    this.setData({
      bannerData: data.banner,
      carousels: data.carousels ? data.carousels : [],
      ads: data.advs,
    });
  },
  chunk(arr, n) {
    var result = [];
    for (var i = 0, len = arr.length; i < len; i += n) {
      result.push(arr.slice(i, i + n));
    }
    return result;
  },
  getMoreData() {
    var that = this;
    if (this.data.page == this.data.total_page) {
      return;
    }
    if (this.data.page >= this.data.total_page) {
      that.setData({
        loading: true,
      });
      return;
    } else {
      this.setData({
        page: this.data.page + 1,
      });
      let urlStr = app.getNetAddresss(
        "plugin.store-cashier.frontend.store.store.get-store-list-to-page"
      );
      let point = app.qqMapTransBMap(
        parseFloat(that.data.point.lng),
        parseFloat(that.data.point.lat)
      );
      urlStr += "&kwd=";
      urlStr += "&lng=" + (point.lng ? point.lng : "");
      urlStr += "&lat=" + (point.lat ? point.lat : "");
      urlStr += "&city_name=" + this.data.city;
      urlStr += "&page=" + this.data.page;
      urlStr += "&is_aggregation=1";
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            var myData = res.data;
            that.setData({
              loading: false,
            });

            if (myData.current_page >= myData.last_page) {
              that.setData({
                loading: true
              });
            }
            that.setData({
              stores: that.data.stores.concat(myData.data)
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              loading: true,
              isLoadMore: false
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  },
  tolocation() {
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation/o2oLocation'
    });
  },
  //banner点击
  bannerClick(e) {
    let item = e.currentTarget.dataset.item;
    if(item&&item.min_url){
      this.goUrl(item.min_url);
    }else{
      wx.showToast({
        title: '请设置链接',
        icon: 'none',
        duration: 2000
      });
    }
  },
  goUrl(url) {
    if (url) {
      try {
        wx.navigateTo({
          url: url
        });
      } catch (e) {
        wx.showToast({
          title: '链接设置错误:' + url,
          icon: 'none',
          duration: 2000
        });
        //TODO handle the exception
      }
    }
  },
  tosearch() {
    if (!this.data.city) {
      wx.showToast({
        icon: 'none',
        title: '请先选择城市',
        duration: 1000
      });
      return;
    }
    wx.navigateTo({
      url: '/packageC/o2o/o2oSearch/o2oSearch?city=' + this.data.city + '&point=' + JSON.stringify(this.data.point)
    });
  },
  getStorePage() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.store.get-store-page");
    let point = app.qqMapTransBMap(parseFloat(that.data.point.lng), parseFloat(that.data.point.lat));
    if(!point.lng){
      point.lng = '',
      point.lat = '';
    }
    // console.log(point)
    that.setData({
      page: 1
    });
    app._getNetWork({
      url: urlStr,
      data: {
        kwd: "",
        lng: point.lng,
        lat: point.lat,
        city_name: that.data.city,
        page: that.data.page
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.store_list) {
            that.getStores(res.data.store_list);
            that.setData({
              openTemplate: res.data.store_list_style || 0
            });
          }else{
            that.setData({
              stores: []
            });
          }
          if(res.data.customer_development){
            // 拓客卡插件开启
            that.setData({
              customer: res.data.customer_development,
              plugin_name:res.data.customer_development_name
            });
          }
          
          let category_10 = that.chunk(res.data.category_list, 10);
          that.setData({
            category: category_10,
            hot_arrondi: res.data.hot_arrondi||{},
            is_sales_display:res.data.is_sales_display,
            open_store_cart: res.data.open_store_cart||false, //store-cart门店购物车聚合页插件
          });
          that._indexData(res.data.get_default);
          that.getShopData(res.data.get_tab);
          that.gettitle();
        } else {
          that.setData({
            stores: [],
            page: 1
          });
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  getShopData(data) {
    this.setData({
      shop: data
    });
    for (let val of this.data.shop) {
      if (val.is_open) {
        this.setData({
          is_open: val.is_open
        });
        break;
      }
    }
    console.log(this.data.is_open,"is_open");
  },
  gotoGrouplist(){
    wx.navigateTo({
      url: '/packageC/o2o/o2oGrouplist/o2oGrouplist'
    });
  },
  toDetail(e){
    let id = e.currentTarget.dataset.id;
    let storeid = e.currentTarget.dataset.storeid;
    wx.navigateTo({
      url: "/packageA/detail_v2/detail_v2?id=" + id +'/'+storeid+ '&name=group'
    });
  },
  tocustomer(e){
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/packageA/detail_v2/detail_v2?id=" + id
    });
  },
  tokerSetMeal(){
    wx.navigateTo({
      url: '/packageH/toker/tokerIndex/tokerIndex?city='+this.data.city+"&point="+JSON.stringify(this.data.point),
    });
  },
  toCartPage(){
    wx.navigateTo({
      url: '/packageG/pages/buy/cart_v2/cart_v2?plugin_id=181'
    });
  }
});
